<template>
  <div>
    <BasicTable @register="registerTable" @resize-column="handleResizeColumn">
      <template #ctlType="{ record }">
        <div>
          {{ record.ctlType }}
        </div>
        <div v-if="record.macroType == 'nest_table' || record.macroType == 'nest_sheet'">
          <div>
            <span class="text-blue-800 cursor-pointer" @click="handleOpenModule(record)"
              >嵌套模块</span
            >:
            <span class="text-blue-800 ml-2 cursor-pointer" @click="handleOpenFormEditor(record)">{{
              record.nestFormName
            }}</span>
          </div>
          <div v-if="record.sourceFormName">
            <span class="text-blue-800 ml-2 cursor-pointer" @click="handleOpenSourceModule(record)"
              >来源模块</span
            >:
            <span
              class="text-blue-800 ml-2 cursor-pointer"
              @click="handleOpenSourceFormEditor(record)"
              >{{ record.sourceFormName }}</span
            >
          </div>
        </div>
        <div v-if="record.macroType == 'module_field_select'">
          <span class="text-blue-800 ml-2 cursor-pointer" @click="handleOpenSourceModule(record)"
            >来源模块</span
          >:
          <span
            class="text-blue-800 ml-2 cursor-pointer"
            @click="handleOpenSourceFormEditor(record)"
            >{{ record.sourceFormName }}</span
          >
        </div>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleSave"> 保存 </a-button>
        <!-- <a-button type="primary" @click="handleCreate"> 新增 </a-button> 
        <a-button type="primary" @click="handleMoreDelete"> 删除 </a-button> -->
      </template>
      <template #bodyCell="{ column }">
        <template v-if="column.dataIndex == 'px'">
          <DragOutlined style="cursor: pointer" />
        </template>
      </template>
      <!-- <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'topRight',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template> -->
      <template #footer>
        <div>
          1、“显示于手机”仅适用于智能模块<br />
          2、“比较”功能已被“验证规则”替代<br />
          3、“辅助”查询表示：如果在查询设置中被选择，则系统不会为此字段自动生成查询，需手动在过滤条件中组装该条件
        </div>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, h, onMounted, ref, PropType } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import { columns, searchFormSchema } from './fieldManagement.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { DragOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getToken } from '/@/utils/auth';
  import { useRouter } from 'vue-router';

  import { getFlowSequenceList, getFlowSequenceDel } from '/@/api/flowManage/flowManage';
  import { getFormGetFieldsForManage, getFormUpdateFields } from '/@/api/formDesign/formDesign';
  export default defineComponent({
    name: 'Notice',
    components: {
      BasicTable,
      TableAction,
      DragOutlined,
    },
    props: {
      name: {
        type: String as PropType<String>,
        default: '',
      },
      formCode: {
        type: String as PropType<String>,
        default: '',
      },
    },
    setup(props) {
      const { createMessage, createConfirm } = useMessage();
      const [registerDrawer, { openDrawer }] = useDrawer();
      const dataSource = ref<Recordable[]>([]);
      const { currentRoute, resolve } = useRouter();
      const { t } = useI18n();
      const [
        registerTable,
        { reload, getSelectRowKeys, setSelectedRowKeys, setTableData, getDataSource, setProps },
      ] = useTable({
        title: '',
        api: getFormGetFieldsForManage,
        columns,
        formConfig: {
          schemas: searchFormSchema,
        },
        searchInfo: {
          op: 'search',
        }, //额外的参数
        useSearchForm: false,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        beforeFetch: (info) => {
          let newInfo = info;
          newInfo.formCode = props.formCode;
          return newInfo;
        },
        rowKey: 'id',
        //   rowSelection: {
        //     type: 'checkbox',
        //   },
        afterFetch: (data) => {
          dataSource.value = data;
          return data;
        },
        pagination: {
          pageSize: 50,
        },
        // actionColumn: {
        //   width: 120,
        //   title: '操作',
        //   dataIndex: 'action',
        //   slots: { customRender: 'action' },
        //   fixed: 'right',
        // },
        customRow: customRow,
      });
      let source = 0; // 源目标数据序号
      let target = 0; // 目标数据序号
      // Table行拖拽
      function customRow(record, index) {
        // 只有当具有管理权限时才启用
        // if (!listPage.value.canUserManage) {
        //   return;
        // }
        return {
          props: {
            // draggable: 'true'
          },
          style: {
            // cursor: 'pointer',
          },
          // 鼠标移入
          onMouseenter: (event) => {
            // event.srcElement.tagName始终为TR，无法区分是点在了哪一列
          },
          onClick: (event) => {
            console.log('onClick', event);
          },
          onMousedown: (event) => {
            console.log('onMousedown-event', event);
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            event.target.parentElement.draggable = true; // 使可以拖动
            // if (event.srcElement.tagName === 'TD') {
            // let cellIndex = event.srcElement.cellIndex;
            // 如果点击的是第1列（第0列为复选框列），则使可以拖动
            // 因拖拽会影响拷贝粘贴，故限制只能在第1列可拖拽
            // if (cellIndex == 1) {
            //   event.target.draggable = true; // 使可以拖动
            // }
            // }
          },
          // 开始拖拽
          onDragstart: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到源目标数据序号
            source = index;
            console.log(record, index, 'source');
          },
          // 拖动元素经过的元素
          onDragover: (event) => {
            // 兼容 IE
            let ev = event || window.event;
            // 阻止默认行为
            ev.preventDefault();
          },
          // 鼠标松开
          onDrop: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到目标数据序号
            target = index;
            // 这里就是让数据位置互换，让视图更新 你们可以看record，index的输出，看是什么
            const dataFrom = dataSource.value[source];
            dataSource.value.splice(source, 1);
            dataSource.value.splice(target, 0, dataFrom);
            setTableData(dataSource.value);
            event.target.parentElement.draggable = false; // 取消拖动
            // console.log(record, index, 'target', source, target);
          },
          onDblclick: () => {
            // handleDbClick(record);
          },
        };
      }
      onMounted(() => {
        setProps({ title: `${props.name}字段` });
        // dataSource.value = [
        //   {
        //     id: 12,
        //   },
        //   {
        //     id: 23,
        //   },
        //   {
        //     id: 35,
        //   },
        //   {
        //     id: 33,
        //   },
        //   {
        //     id: 85,
        //   },
        // ];
        // setTableData(dataSource.value);
      });

      function handleCreate() {
        openDrawer(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openDrawer(true, {
          record,
          isUpdate: true,
        });
      }

      const handleMoreDelete = () => {
        const selectRowKeys = getSelectRowKeys();
        if (selectRowKeys.length == 0) {
          return createMessage.warning('请选择数据');
        }
        const ids = selectRowKeys.join(',');
        deleteAction(ids);
      };

      const handleDelete = (record: Recordable) => {
        deleteAction(record.id);
      };

      const deleteAction = (ids) => {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要删除么'),
          onOk: async () => {
            try {
              const params = {
                ids: ids,
              };
              await getFlowSequenceDel(params);
              createMessage.success('操作成功');
              handleSuccess();
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      };

      function handleSuccess() {
        setSelectedRowKeys([]);
        reload();
      }

      const handleMove = () => {};
      const handleSave = async () => {
        console.log('getDataSource', getDataSource());
        try {
          setProps({ loading: true });
          let params = {
            formCode: props.formCode,
            fields: getDataSource(),
          };
          await getFormUpdateFields(params);
          createMessage.success('操作成功');
        } finally {
          setProps({ loading: false });
        }
      };

      function handleOpenModule(record) {
        let routeUrl: any = {};
        routeUrl = resolve({
          path: '/moduleSetup',
          query: {
            moduleCode: record.nestModuleCode,
            formCode: record.nestFormCode,
            pageName: record.nestModuleName,
            token: getToken() as any,
          },
        });
        const height = screen.height;
        const width = screen.width;
        window.open(
          routeUrl.href,
          '',
          `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        );
      }

      function handleOpenFormEditor(record) {
        let routeUrl: any = {};
        routeUrl = resolve({
          path: '/formEditor',
          query: {
            formCode: record.nestFormCode,
            pageName: record.nestFormName,
            token: getToken() as any,
          },
        });
        const height = screen.height;
        const width = screen.width;
        window.open(
          routeUrl.href,
          '',
          `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        );
      }

      function handleOpenSourceModule(record) {
        let routeUrl: any = {};
        routeUrl = resolve({
          path: '/moduleSetup',
          query: {
            moduleCode: record.sourceModuleCode,
            formCode: record.sourceFormCode,
            pageName: record.sourceModuleName,
            token: getToken() as any,
          },
        });
        const height = screen.height;
        const width = screen.width;
        window.open(
          routeUrl.href,
          '',
          `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        );
      }

      function handleOpenSourceFormEditor(record) {
        let routeUrl: any = {};
        routeUrl = resolve({
          path: '/formEditor',
          query: {
            formCode: record.sourceFormCode,
            pageName: record.sourceFormName,
            token: getToken() as any,
          },
        });
        const height = screen.height;
        const width = screen.width;
        window.open(
          routeUrl.href,
          '',
          `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        );
      }

      return {
        registerTable,
        registerDrawer,
        handleCreate,
        handleEdit,
        handleMoreDelete,
        handleDelete,
        handleSuccess,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        handleMove,
        dataSource,
        handleSave,
        handleOpenModule,
        handleOpenFormEditor,
        handleOpenSourceModule,
        handleOpenSourceFormEditor,
      };
    },
  });
</script>
